<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Vue.js</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <link rel="stylesheet" href="style.css" />
    <script src="vue.js"></script>
  </head>
  <body onload="draw()">
    <div id="vue-app"></div>
    <canvas id="canvas" width="400" height="300">
      你这浏览器不支持这玩意啊
    </canvas>
    <script src="app.js"></script>
    <script>
      function draw() {
        // 让vscode可以显示canvas智能提示
        /** @type {HTMLCanvasElement} */
        const canvas = document.getElementById('canvas')
        if (canvas.getContext) {
          const ctx = canvas.getContext('2d')
          /**
           * canvas 动画原理
           * 1.绘制图像
           * 2.清除图像
           * 3.更新位置
           * 4.重绘
           */
          let x = 0,
            y = 0,
            width = 10,
            height = 10
          ctx.fillRect(x, y, width, height)

          //速度
          let speedX = 20
          let speedY = 20

          function optimize() {
            // 2.清除图像
            ctx.clearRect(0, 0, canvas.width, canvas.height)
            // 3.更新位置
            x += speedX
            if (x > canvas.width - width) {
              // rebound
              speedX *= -1
            } else if (x < 0) {
              speedX *= -1
            }

            y += speedY
            if (y > canvas.height - height) {
              // rebound
              speedY *= -1
            } else if (y < 0) {
              speedY *= -1
            }

            // 4.绘制图像
            ctx.fillRect(x, y, width, height)
            // 递归调用
            window.requestAnimationFrame(optimize)
          }
        }
        optimize()
      }
    </script>
  </body>
</html>
